﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace OrBitDataModule.Common
{
    public static class LocalSetting
    {
        private readonly static string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.xml");
        static LocalSetting()
        {
            // 如果文件不存在，创建一个空的XML文件
            if (!File.Exists(filePath))
            {
                CreateEmptyXmlFile();
            }
        }
        /// <summary>
        /// 获取所有配置项
        /// </summary>
        /// <returns></returns>
        public static List<(string uniqueId, bool autoStart, Dictionary<string, string> parameters)> GetAllConfigs()
        {
            XDocument xDocument = XDocument.Load(filePath);

            var allConfigs = xDocument.Root.Elements("Config")
                .Select(e =>
                {
                    string uniqueId = e.Attribute("UniqueId")?.Value;
                    bool autoStart = bool.TryParse(e.Attribute("AutoStart")?.Value, out bool result) && result;
                    var parameters = e.Elements("Parameter")
                                      .ToDictionary(p => p.Attribute("Key")?.Value, p => p.Attribute("Value")?.Value);
                    return (uniqueId, autoStart, parameters);
                }).ToList();

            return allConfigs;
        }

        /// <summary>
        /// 清理孤儿数据
        /// </summary>
        /// <param name="list"></param>
        public static void CleanOrphanData(List<string> list)
        {
            XDocument xDocument = XDocument.Load(filePath);
            IEnumerable<XElement> configElements = xDocument.Root.Elements("Config");
            foreach (XElement config in configElements.ToList())
            {
                string uniqueId = config.Attribute("UniqueId")?.Value;
                if (!list.Contains(uniqueId))
                {
                    config.Remove();
                }
            }
            xDocument.Save(filePath);
        }

        /// <summary>
        /// 检查配置项是否存在
        /// </summary>
        /// <param name="uniqueId"></param>
        /// <returns></returns>
        public static bool CheckConfigExists(string uniqueId)
        {
            XDocument xDocument = XDocument.Load(filePath);
            XElement configElement = xDocument.Root.Elements("Config")
                .FirstOrDefault(e => e.Attribute("UniqueId")?.Value == uniqueId);
            return configElement != null;
        }

        /// <summary>
        /// 添加配置项
        /// </summary>
        /// <param name="uniqueId"></param>
        /// <param name="autoStart"></param>
        /// <param name="parameters"></param>
        public static void AddConfig(string uniqueId, bool autoStart, Dictionary<string, string> parameters = null)
        {
            XDocument xDocument = XDocument.Load(filePath);
            XElement configElement = xDocument.Root.Elements("Config")
                .FirstOrDefault(e => e.Attribute("UniqueId")?.Value == uniqueId);

            if (configElement == null)
            {
                // 如果不存在，创建新的配置项
                XElement newConfig = new XElement("Config",
                    new XAttribute("UniqueId", uniqueId),
                    new XAttribute("AutoStart", autoStart.ToString()));

                if (parameters != null)
                {
                    foreach (var param in parameters)
                    {
                        newConfig.Add(new XElement("Parameter",
                            new XAttribute("Key", param.Key),
                            new XAttribute("Value", param.Value)));
                    }
                }

                xDocument.Root.Add(newConfig);
            }
            else
            {
                // 如果存在，更新现有配置项
                configElement.SetAttributeValue("AutoStart", autoStart.ToString());

                if (parameters != null)
                {
                    foreach (var param in parameters)
                    {
                        XElement paramElement = configElement.Elements("Parameter")
                            .FirstOrDefault(p => p.Attribute("Key")?.Value == param.Key);

                        if (paramElement != null)
                        {
                            paramElement.SetAttributeValue("Value", param.Value);
                        }
                        else
                        {
                            configElement.Add(new XElement("Parameter",
                                new XAttribute("Key", param.Key),
                                new XAttribute("Value", param.Value)));
                        }
                    }
                }
            }

            xDocument.Save(filePath);
        }

        /// <summary>
        /// 更新配置项
        /// </summary>
        /// <param name="uniqueId"></param>
        /// <param name="autoStart"></param>
        /// <param name="parameters"></param>
        public static void UpdateConfig(string uniqueId, bool autoStart, Dictionary<string, string> parameters = null)
        {
            XDocument xDocument = XDocument.Load(filePath);
            XElement configElement = xDocument.Root.Elements("Config")
                .FirstOrDefault(e => e.Attribute("UniqueId")?.Value == uniqueId);

            if (configElement == null)
            {
                // 如果不存在，创建新的配置项
                XElement newConfig = new XElement("Config",
                    new XAttribute("UniqueId", uniqueId),
                    new XAttribute("AutoStart", autoStart.ToString()));

                if (parameters != null)
                {
                    foreach (var param in parameters)
                    {
                        newConfig.Add(new XElement("Parameter",
                            new XAttribute("Key", param.Key),
                            new XAttribute("Value", param.Value)));
                    }
                }

                xDocument.Root.Add(newConfig);
            }
            else
            {
                // 如果存在，更新现有配置项
                configElement.SetAttributeValue("AutoStart", autoStart.ToString());
                configElement.Elements("Parameter")?.Remove();
                if (parameters != null)
                {
                    foreach (var param in parameters)
                    {
                        XElement paramElement = configElement.Elements("Parameter")
                            .FirstOrDefault(p => p.Attribute("Key")?.Value == param.Key);


                        if (paramElement != null)
                        {
                            paramElement.SetAttributeValue("Value", param.Value);
                        }
                        else
                        {
                            configElement.Add(new XElement("Parameter",
                                new XAttribute("Key", param.Key),
                                new XAttribute("Value", param.Value)));
                        }
                    }
                }
            }

            xDocument.Save(filePath);
        }
        /// <summary>
        /// 删除配置项
        /// </summary>
        /// <param name="uniqueId"></param>
        /// <returns></returns>
        public static bool RemoveConfig(string uniqueId)
        {
            XDocument xDocument = XDocument.Load(filePath);
            XElement configElement = xDocument.Root.Elements("Config")
                .FirstOrDefault(e => e.Attribute("UniqueId")?.Value == uniqueId);

            if (configElement != null)
            {
                configElement.Remove();
                xDocument.Save(filePath);
                return true; // 移除成功
            }

            return false; // 未找到对应的配置项
        }
        /// <summary>
        /// 获取配置项
        /// </summary>
        /// <param name="uniqueId"></param>
        /// <returns></returns>
        public static (bool result, Dictionary<string, string> parameters) GetConfig(string uniqueId)
        {
            XDocument xDocument = XDocument.Load(filePath);
            XElement configElement = xDocument.Root.Elements("Config")
                .FirstOrDefault(e => e.Attribute("UniqueId")?.Value == uniqueId);

            if (configElement != null)
            {
                var parameters = configElement.Elements("Parameter")
                    .ToDictionary(p => p.Attribute("Key")?.Value, p => p.Attribute("Value")?.Value);

                bool result = bool.TryParse(configElement.Attribute("AutoStart")?.Value, out bool autoStart) && autoStart;
                return (result, parameters);
            }
            return (false, new Dictionary<string, string>());
        }
        /// <summary>
        /// 创建空的XML文件
        /// </summary>
        private static void CreateEmptyXmlFile()
        {
            XDocument xDocument = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("Configs"));

            xDocument.Save(filePath);
        }
    }
}
